import api from "./api.js";
function req(url, data = {},method = "POST",type ) {
	getApp().globalData.lodingFlag = true
	return new Promise(function(resolve, reject) {
		data.token = uni.getStorageSync('userInfo').token || "";
		console.log(uni.getStorageSync('userInfo').token,'token')
		uni.request({
			url,
			data,
			method,
			header: {
				'content-type': type?type:'application/x-www-form-urlencoded'
			},
			success: function(res) {
			},
			fail: function(err) {
				reject(err);
			},
			complete: function(res) {
				if (res.data.code == 1) {
					resolve(res.data.data);
				}else{
					log(res.data.msg)
					if(res.data.code == 401){
						uni.reLaunch({
							url:'/pages/login/index'
						})
					}
				}
			}
		})
	});
}
// 时间戳转化格式
function formatDate(str, format) {
	const date = new Date(str*1000);
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	if (format == 'YMD') {
		return `${[year, month, day].map(formatNumber).join('-')}`
	} else {
		return `${[year, month, day].map(formatNumber).join('-')} ${[hour, minute,second].map(formatNumber).join(':')}`
	}
}
const formatNumber = n => {
	n = n.toString()
	return n[1] ? n : `0${n}`
}
// 时间戳转化日时月秒
function formatTime(time) {
	let day, hour, minute, second;
	time = time/1000;
	day = Math.floor(time / (60 * 60 * 24))
	hour = Math.floor(time / (60 * 60)) - (day * 24)
	minute = Math.floor(time / 60) - (day * 24 * 60) - (hour * 60)
	second = Math.floor(time) - (day * 24 * 60 * 60) - (hour * 60 * 60) - (minute * 60)
	return `${day},${[ hour, minute, second].map(formatNumber).join(',')}`
}

function go(url, type = 1){
	if(!url) return
	if(type == 3){
		uni.switchTab({url})
	}else if(type == 1){
		uni.navigateTo({url})
	}
}
function log(title, icon = 'none', duration= 1500){
	uni.showToast({
		title,
		icon,
		duration
	})
}
function verify(obj){
	return new Promise((resolve,jevect)=>{
		let s = !obj.account || !obj.password?false: true
		// let s = !obj.account || !/^1[3456789]\d{9}$/.test(obj.account) || !obj.password?false: true
		if(!s) log(!obj.account?'请填写手机号/账号':!obj.password?'请填写密码':'请输入正确手机号/账号')
		resolve(s)
	})
}

module.exports = {
	req,
	formatDate,
	formatTime,
	go,
	log,
	verify
}
